ReactJS Ultra For Beginners
🎯 The useRef Hook
What is useRef?
- A React Hook that returns a mutable ref object
- Persists between re-renders without causing re-renders
- Used to access DOM elements directly
- Can store any mutable value
📝 Basic Syntax
import { useRef } from "react"; function TextInputWithFocusButton() { const inputRef = useRef(null); const focusInput = () => { inputRef.current.focus(); }; return ( <> <input ref={inputRef} type="text" /> <button onClick={focusInput}>Focus the input</button> </> ); }
🔑 Core Concepts
1. Creating a Ref:
const myRef = useRef(initialValue);
2. Accessing the Ref:
// Access the current value console.log(myRef.current); // Update the current value myRef.current = newValue;
3. Attaching to DOM Elements:
<input ref={inputRef} /> <div ref={divRef} /> <video ref={videoRef} />
🎯 Common Use Cases
1. Focus Management:
function LoginForm() { const emailRef = useRef(null); const passwordRef = useRef(null); const handleEmailSubmit = (e) => { e.preventDefault(); passwordRef.current.focus(); }; const handlePasswordSubmit = (e) => { e.preventDefault(); // Handle login }; return ( <form> <input ref={emailRef} type="email" placeholder="Email" onKeyDown={(e) => e.key === "Enter" && handleEmailSubmit(e)} /> <input ref={passwordRef} type="password" placeholder="Password" onKeyDown={(e) => e.key === "Enter" && handlePasswordSubmit(e)} /> </form> ); }
2. Measuring DOM Elements:
function MeasureElement() { const elementRef = useRef(null); const [dimensions, setDimensions] = useState({ width: 0, height: 0 }); useEffect(() => { if (elementRef.current) { const rect = elementRef.current.getBoundingClientRect(); setDimensions({ width: rect.width, height: rect.height, }); } }, []); return ( <div ref={elementRef}> <p>Width: {dimensions.width}px</p> <p>Height: {dimensions.height}px</p> </div> ); }
3. Storing Previous Values:
function Counter() { const [count, setCount] = useState(0); const prevCountRef = useRef(); useEffect(() => { prevCountRef.current = count; }); const prevCount = prevCountRef.current; return ( <div> <p>Current: {count}</p> <p>Previous: {prevCount}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); }
4. Video/Audio Controls:
function VideoPlayer() { const videoRef = useRef(null); const play = () => { videoRef.current.play(); }; const pause = () => { videoRef.current.pause(); }; const skipTo = (seconds) => { videoRef.current.currentTime = seconds; }; return ( <div> <video ref={videoRef} src="video.mp4" /> <button onClick={play}>Play</button> <button onClick={pause}>Pause</button> <button onClick={() => skipTo(30)}>Skip to 30s</button> </div> ); }
🔧 Advanced Patterns
Custom Hook for Previous Value:
function usePrevious(value) { const ref = useRef(); useEffect(() => { ref.current = value; }); return ref.current; } // Usage function Counter() { const [count, setCount] = useState(0); const prevCount = usePrevious(count); return ( <div> <p>Current: {count}</p> <p>Previous: {prevCount}</p> <button onClick={() => setCount(count + 1)}>Increment</button> </div> ); }
Imperative Handle Pattern:
import { forwardRef, useImperativeHandle, useRef } from "react"; const FancyInput = forwardRef((props, ref) => { const inputRef = useRef(); useImperativeHandle(ref, () => ({ focus: () => { inputRef.current.focus(); }, blur: () => { inputRef.current.blur(); }, select: () => { inputRef.current.select(); }, })); return <input ref={inputRef} {...props} />; }); // Usage function Form() { const inputRef = useRef(); const handleClick = () => { inputRef.current.focus(); }; return ( <div> <FancyInput ref={inputRef} /> <button onClick={handleClick}>Focus Input</button> </div> ); }
Storing Mutable Values:
function Timer() { const [count, setCount] = useState(0); const intervalRef = useRef(null); const startTimer = () => { intervalRef.current = setInterval(() => { setCount((c) => c + 1); }, 1000); }; const stopTimer = () => { if (intervalRef.current) { clearInterval(intervalRef.current); intervalRef.current = null; } }; useEffect(() => { return () => { if (intervalRef.current) { clearInterval(intervalRef.current); } }; }, []); return ( <div> <p>Count: {count}</p> <button onClick={startTimer}>Start</button> <button onClick={stopTimer}>Stop</button> </div> ); }
⚠️ Important Notes
1. Refs Don't Trigger Re-renders:
// This won't cause a re-render myRef.current = newValue; // This will cause a re-render setState(newValue);
2. Initial Value:
const ref = useRef(null); // null is common for DOM refs const ref = useRef(0); // 0 for number values const ref = useRef({}); // {} for object values
3. Cleanup:
useEffect(() => { const timer = setInterval(() => { // Do something }, 1000); return () => { clearInterval(timer); // Clean up }; }, []);
🎯 Best Practices
- Use refs sparingly - prefer state when possible
- Always clean up timers and subscriptions
- Check if ref.current exists before using
- Use forwardRef for component refs
- Don't use refs for values that should trigger re-renders
111 / 111 videos100% complete
Course Completed!
Great job! You've finished all videos.
Welcome to the Course
Intro to The Course
3:33How to Learn This Course
3:02What is React and Why You Should Learn It?
4:14Getting Started with React
Installing Nodejs
3:03Setting up a React Development Environment
4:30VSCode Extensions
3:17JavaScript Refresher - All JS You Need To Know Before React
Functions
5:39Ternary and Logical Operators
7:21Objects and Arrays
7:11Map and Filter Functions
7:15Array Function Key Prop
3:13String Templating
4:27Basic React Concepts
React Project Folder Structure
6:55An Intro To JSX
10:33What is the App Component?
2:46How to use Components?
10:23Lists in React
9:45CSS in React
9:10Component Project - Build A Simple Website
First React Project
3:34Making A Navbar
7:11Displaying Images
7:11Making the About Us Section
2:35Creating A Footer
3:38Intro To States In React
What is the useState Hook?
10:38What is the useState Hook? Part 2
4:42What is the useState Hook? Part 3
14:50Intro React Project - Task Tracker App
Beginner Project - Task Tracker App
35:03React Component Lifecycle
The Virtual Dom
1:50React Component Lifecycle
1:42The useEffect Hook
15:40The useEffect Hook Part 2
8:41Routing in React
React Router
14:05React Router Part 2
14:28Advanced Forms In React
Forms in React - React Hook Form
25:36State Management
Intro To State Management - Global States
18:37Beginner Project - Build A Blog App
Intermediate Project - Build A Blog App
40:40Intermediate Project - Build A Blog App Part 2
26:57Other Useful React Hooks
Rules of Hooks
4:05Learn the useReducer Hook
9:54Learn the useRef Hook
12:03Making Your Own Custom Hook
12:10